package com.java.base.exercise.jvm;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author RenPu
 * @Date 2021/10/22 14:36
 * @Version 1.0
 * @Description: 做所属类型检查返回false, 原因存在俩个Class类，一个是我们自定的类加载器加载同一个Class生成的类，
 * 另一个类则是系统应用程序类加载器，生成的类。
 **/
public class ClassLoaderTest {

    public static void main(String[] args) throws Exception {
        ClassLoader classLoader = new ClassLoader() {
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                try {
                    String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
                    InputStream is = getClass().getResourceAsStream(fileName);
                    if (is == null) {
                        return super.loadClass(name);
                    }
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    return defineClass(name, b, 0, b.length);
                } catch (IOException e) {
                    throw new ClassNotFoundException(name);
                }
            }
        };

        Object o = classLoader.loadClass("com.java.base.exercise.jvm.ClassLoaderTest").newInstance();
        System.out.println(o.getClass());
        System.out.println(o instanceof com.java.base.exercise.jvm.ClassLoaderTest);


//        ClassLoader myLoader=new ClassLoader(){
//            @Override
//            public Class<?>loadClass(String name)throws ClassNotFoundException{
//                try{
//                    String fileName=name.substring(name.lastIndexOf(".")+1)+".class";
//                    InputStream is=getClass().getResourceAsStream(fileName);
//                    if(is==null){
//                        return super.loadClass(name);
//                    }
//                    byte[]b=new byte[is.available()];
//                    is.read(b);
//                    return defineClass(name,b,0,b.length);
//                }catch(IOException e){
//                    throw new ClassNotFoundException(name);
//                }
//            }
//        };
//        Object obj=myLoader.loadClass("com.java.base.exercise.jvm.ClassLoaderTest").newInstance();
//        System.out.println(obj.getClass());
//        System.out.println(obj instanceof com.java.base.exercise.jvm.ClassLoaderTest);


    }


}
